package org.example.socket;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.IoFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.apache.log4j.Logger;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

public class ClientSocketManager {
    private static Logger logger = Logger.getLogger(ClientSocketManager.class);
    private NioSocketConnector connector;
    private IoSession mIoSession;
    private static ClientSocketManager instance = new ClientSocketManager();
    private ClientSocketManager() {}

    public static ClientSocketManager getInstance(){
        return instance;
    }
    public void initSocket(String ip,IoFutureListener<IoFuture> ioFutureListener) {
        connector = new NioSocketConnector();
        connector.setHandler(new ClientSocketHandler());
        DefaultIoFilterChainBuilder chain = connector.getFilterChain();
        chain.addLast("logger", new LoggingFilter());
        chain.addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"), LineDelimiter.NUL, LineDelimiter.NUL)));
        IoFuture connFuture = connector.connect(new InetSocketAddress(
                "127.0.0.1", 1234));
        connFuture.addListener(ioFutureListener);
    }

    public void setIoSession(IoSession ioSession) {
        mIoSession = ioSession;
    }

    public IoSession getSession() {
        return mIoSession;
    }

    public void sendData(Object obj) {
        if (mIoSession != null && mIoSession.isConnected()) {
            mIoSession.write(obj);
        }
    }
}
